#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

const std::string filename = "./fifo";
const int fileread = O_RDONLY;
const int filewrite = O_WRONLY;
const int readsize = 1024;
const mode_t fmode = 0600;
const int defaultfd = -1;

static int fd;

class Fifo
{
private:
    void OpenPipe()
    {
        _fd = ::open(filename.c_str(), fileread | filewrite);
        if (_fd < 0)
        {
            std::cerr << "open error" << std::endl;
        }
    }

public:
    Fifo() : _fd(-1)
    {
        umask(0);
        int n = ::mkfifo(filename.c_str(), fmode);
        if (n < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
        }
        std::cout << "mkfifo success" << std::endl;
    }

    // 读的方式打开文件
    void OpenPipeRead()
    {
        fd = ::open(filename.c_str(), fileread);
        if (fd < 0)
        {
            std::cerr << "open error" << std::endl;
        }
    }

    // 写的方式打开文件
    int OpenPipeWrite()
    {
        fd = ::open(filename.c_str(), filewrite);
        if (fd < 0)
        {
            std::cerr << "open error" << std::endl;
            return -1;
        }
        return fd;
    }

    //读端
    int Wait()
    {
        int code = 1;
        ssize_t n = ::read(_fd, &code,sizeof(code));
        if(n==sizeof(code))
            return 1;
        else if(n==0)
            return 2;
        return 0;
    }

    //写端
    ssize_t Singal()
    {
        int code = 1;
        return ::write(_fd, &code,sizeof(code));
    }

    ~Fifo()
    {
        if (_fd >= 0)
            ::close(_fd);
        int flag = ::unlink(filename.c_str());
        if (flag < 0)
        {
            std::cerr << "unlink error" << std::endl;
            return;
        }
        std::cout << "unlink success" << std::endl;
    }

private:
    int _fd;
};


Fifo fifo;